import get from '@dfeidao/atom-web/local/get';
import fire from '@dfeidao/atom-web/msg/fire';
import nodejs from '@dfeidao/atom-web/msg/nodejs';
import error from '@dfeidao/atom-web/msgbox/error';
import success from '@dfeidao/atom-web/msgbox/success';
import { IFeidaoAiBrowserComponent } from '@dfeidao/web/interfaces';
import hide_loading from '../../atom/hide-loading';
import show_loading from '../../atom/show-loading';

interface Aa {
	id: string;
	role_no: string;
	role_name: string;
	icon: string;
	role_allot_id: string;
}
export default async function a002(fd: IFeidaoAiBrowserComponent, args: { currentTarget: HTMLInputElement }) {
	//  合并
	const target_node = args.currentTarget as HTMLInputElement;
	const productid = get(fd, 'productid');
	const role = get(fd, 'role') as Aa;
	const role_no = role.role_no;
	const role_allot_id = get(fd, 'role_allot_id') as Aa;

	const c_boxs = fd.data.node.querySelectorAll('[data-feidao-name="list_checkbox"]:checked');
	if (c_boxs.length <= 1) {
		error('请勾选至少两条数据！');
		return;
	}
	const ids = Array.from(c_boxs).map((item) => {
		return item.getAttribute('data-feidao-id4');
	});

	const group_id = Array.from(c_boxs).map((item) => {
		return item.getAttribute('data-feidao-group_id');
	});
	const query1 = { productid, role_allot_id, group_id };
	// const count = await nodejs(url, './permissions/allot_conditions_group_find2', query1, false, false);
	show_loading();
	const count = await nodejs('roler/service/allot_conditions_group_find2', query1);
	hide_loading();
	if (count !== 0) {
		error('合并后的数据不能再次合并！');
		return;
	}
	const connector = Array.from(c_boxs).map((item) => {
		return item.getAttribute('data-feidao-connector');
	});
	const resultarr = [...new Set(connector)];
	// console.log(resultarr);
	if (resultarr.length > 1 || !resultarr[0]) {
		error('连接符相同且不能都为空才能合并！');
		return;
	}

	let priority;
	if (target_node.name === 'qian') {
		priority = parseInt(c_boxs[0].getAttribute('data-feidao-priority'), 10);
	} else {
		priority = parseInt(c_boxs[c_boxs.length - 1].getAttribute('data-feidao-priority'), 10);
	}
	const query = { ids, priority, productid, role_allot_id, role_no };
	show_loading();
	const res = await nodejs('roler/service/allot_conditions_group_add1', query);
	hide_loading();
	if (res === 'success') {
		fire('zj-000011', 'ec-003', { role_allot_id, str: 'hebing' });
		success('合并成功！');
	} else {
		error('合并失败！');
	}
}
